package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;

@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {
@Autowired
    ApUserMapper apUserMapper;
    @Override
    public ResponseResult login(LoginDTO dto) {
        String phone = dto.getPhone();
        String password = dto.getPassword();
        if (StringUtils.isNotBlank(password)&&StringUtils.isNotBlank(phone)){
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, phone));
            if (apUser==null){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
            }
            String s = DigestUtils.md5DigestAsHex((password + apUser.getSalt()).getBytes());
            if (!s.equals(apUser.getPassword())){
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"密码错误");
            }
            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
            HashMap map = new HashMap();
            map.put("token",token);
            apUser.setPassword("");
            apUser.setSalt("");
            map.put("user",apUser);
            return ResponseResult.okResult(map);
        }else{
            if (dto.getEquipmentId()==null){
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户名密码和设备ID全部为空");
            }
            HashMap map = new HashMap();
            map.put("token",AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }
    }
}